package com.cn.byjk.baseServer;

import com.cn.byjk.config.RabbitConfig;
import com.cn.byjk.config.RabbitExchangeConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author zhangdianzhi
 * @version v1.0
 * @description 消息队列接收者
 * @date 2022/1/6 12:16
 */
@Component
public class RabbitReceive {
        @Autowired
        private RabbitConfig rabbitConfig;

        @Autowired
        private RabbitExchangeConfig rabbitExchangeConfig;

        @Bean
        public SimpleMessageListenerContainer messageContainer() {
            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(rabbitConfig.connectionFactory());
            container.setQueues(rabbitExchangeConfig.queue()); //设置要监听的队列
            container.setExposeListenerChannel(true);
            container.setMaxConcurrentConsumers(1);
            container.setConcurrentConsumers(1);
            container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
            container.setMessageListener(new ChannelAwareMessageListener() {
                @Override
                public void onMessage(Message message, Channel channel) throws Exception {
                    byte[] body = message.getBody();
                    System.out.println("receive msg : " + new String(body));
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
                }
            });
            return container;
        }

}
